<!-- 用户状态总览表图形 -->
<template>
  <div class="chart-container">
    <!-- 创建一个响应式引用来保存 DOM 元素  折线图-->
    <div class="chart-line" ref="lineChart"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from "vue";
import * as echarts from "echarts";
import axios from 'axios';
import UserStatisticsApi from "@/api/Backend/userStatisticsApi";

onUnmounted(() => {
  if (myLineChart && myLineChart.dispose) {
    myLineChart.dispose();
  }
});
import {
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
} from "echarts/components";
import { LineChart, PieChart } from "echarts/charts";
import { UniversalTransition, LabelLayout } from "echarts/features";
import { CanvasRenderer } from "echarts/renderers";

echarts.use([
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  LineChart,
  CanvasRenderer,
  UniversalTransition,
  PieChart,
  CanvasRenderer,
  LabelLayout,
]);

// 创建一个响应式引用来保存 DOM 元素
const lineChart = ref(null);
let myLineChart = null;

// 初始化 ECharts 实例并设置配置项
onMounted(async () => {
  // 确保 DOM 已经渲染完成
  await nextTick();
  //初始化 ECharts 引入echarts
  myLineChart = echarts.init(lineChart.value);
try{ 
 // 4. 调用后端接口（需和 Spring Boot 接口地址匹配，可配置代理解决跨域）
    const res = await UserStatisticsApi.getUserStatistics(); 
    console.log(res);
    // const res = await axios.get("/api/userStatistics/last7days"); 
     const { dates, newUserCounts, activeUserCounts } = res;
  // 设置折线图 图表
  const optionLine = {
    title: {
      text: "用户总览",
    },
    tooltip: {
      trigger: "axis",
    },
    // 这里的数据 需要和下面series 里的name保持一致
    legend: {
      data: ["新增用户", "活跃用户"],
    },
    grid: {
      left: "4%",
      right: "8%",
      bottom: "5%",
      containLabel: true,
    },
    toolbox: {
      feature: {
        saveAsImage: {},
      },
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: dates,
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "新增用户",
        type: "line",
        // stack: "Total",
        data: newUserCounts,
      },
      {
        name: "活跃用户",
        type: "line",
        // stack: "Total",
        data: activeUserCounts,
      },
      ],
  };
  optionLine && myLineChart.setOption(optionLine);
} catch (error) {
  console.log(error);
}
});
</script>

<style scoped>
.chart-container {
  display: flex;
  width: 100%;
  height: 100%;
}

.chart-line {
  width: 100%;
  height:350px;
}

.chart-pie {
  width: 450px;
  height: 400px;
}
</style>
